from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model

# 获取用户模型
User = get_user_model()

class NoteManager(models.Manager):
    """笔记管理器"""
    def pinned_notes(self):
        """置顶笔记"""
        return self.filter(is_pinned=True)

    def unpinned_notes(self):
        """返回所有未置顶笔记"""
        return self.filter(is_pinned=False)

    def by_user(self, user):
        """用户笔记"""
        return self.filter(user=user)

    def by_ai_status(self, status):
        """按AI处理状态查询"""
        return self.filter(ai_processing_status=status)


class Note(models.Model):
    """备忘录模型"""
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE,
        related_name='notes',
        verbose_name='用户',
        db_constraint=True,
        db_index=True
    )
    title = models.CharField(max_length=200, verbose_name="标题")
    content = models.TextField(verbose_name="内容")
    
    # 计划相关字段
    plan_type = models.CharField(
        max_length=20,
        choices=[
            ('task', '任务'),
            ('meeting', '会议'),
            ('exam', '考试'),
            ('project', '项目'),
            ('reminder', '提醒'),
            ('general', '普通')
        ],
        default='general',
        verbose_name="计划类型"
    )
    
    status = models.CharField(
        max_length=20,
        choices=[
            ('pending', '待处理'),
            ('in_progress', '进行中'),
            ('completed', '已完成'),
            ('cancelled', '已取消')
        ],
        default='pending',
        verbose_name="状态"
    )
    
    priority = models.CharField(
        max_length=10,
        choices=[
            ('high', '高'),
            ('medium', '中'),
            ('low', '低')
        ],
        default='medium',
        verbose_name="优先级"
    )
    
    start_time = models.DateTimeField(null=True, blank=True, verbose_name="开始时间")
    end_time = models.DateTimeField(null=True, blank=True, verbose_name="结束时间")
    reminder_time = models.DateTimeField(null=True, blank=True, verbose_name="提醒时间")
    
    # 进度相关
    progress = models.IntegerField(default=0, verbose_name="进度")
    checklist = models.JSONField(default=list, verbose_name="检查清单")
    
    # AI 增强功能
    ai_processing_status = models.CharField(
        max_length=20,
        choices=[
            ('pending', '待处理'),
            ('processing', '处理中'),
            ('completed', '已完成'),
            ('failed', '失败')
        ],
        default='pending',
        verbose_name="AI处理状态"
    )
    ai_summary = models.TextField(null=True, blank=True, verbose_name="AI生成摘要")
    ai_suggestions = models.JSONField(
        default=dict, 
        verbose_name="AI建议",
        help_text="包含时间管理、任务分解等建议"
    )
    ai_keywords = models.JSONField(
        default=list,
        verbose_name="关键词",
        help_text="AI提取的关键词"
    )
    
    # 关联信息
    related_users = models.ManyToManyField(
        User, 
        related_name='related_notes',
        blank=True,
        verbose_name="相关用户"
    )
    parent_note = models.ForeignKey(
        'self',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='sub_notes',
        verbose_name="父备忘录"
    )
    
    # 元数据
    is_pinned = models.BooleanField(default=False, verbose_name="是否置顶")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    last_ai_process_time = models.DateTimeField(
        null=True, 
        blank=True,
        verbose_name="最后AI处理时间"
    )

    # 添加新字段
    note_type = models.CharField(
        max_length=50, 
        default='general',
        choices=[
            ('general', '普通笔记'),
            ('study', '学习笔记'),
            ('work', '工作笔记'),
            ('plan', '计划笔记'),
        ]
    )
    is_ai_generated = models.BooleanField(default=False)

    # 添加与Tag的多对多关系
    tags = models.ManyToManyField(
        'Tag',
        through='NoteTag',
        related_name='notes'
    )

    objects = NoteManager() # 使用自定义管理器

    def __str__(self):
        return self.title # 返回笔记的标题作为模型的字符串表示

    class Meta:
        db_table = 'note'  # 数据库表名
        verbose_name = '备忘录'  # 单数形式显示名称
        verbose_name_plural = '备忘录'  # 复数形式显示名称
        ordering = ['-is_pinned', '-updated_at']
        indexes = [
            models.Index(fields=['plan_type', 'status']),
            models.Index(fields=['ai_processing_status']),
            models.Index(fields=['created_at'])
        ]

    def request_ai_processing(self):
        """请求AI处理"""
        self.ai_processing_status = 'processing'
        self.save()

    def update_ai_results(self, summary, suggestions, keywords):
        """更新AI处理结果"""
        self.ai_summary = summary
        self.ai_suggestions = suggestions
        self.ai_keywords = keywords
        self.ai_processing_status = 'completed'
        self.last_ai_process_time = timezone.now()
        self.save()

class Tag(models.Model):
    """标签模型"""

    id = models.BigAutoField(primary_key=True)  # 标签唯一标识，自动递增
    name = models.CharField(max_length=100, unique=True, verbose_name="标签名称")  # 标签名称，唯一
    description = models.TextField(blank=True, null=True, verbose_name="标签描述")  # 标签描述，可为空
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")  # 自动添加创建时间
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")  # 自动更新更新时间
    is_active = models.BooleanField(default=True, verbose_name="是否激活")  # 是否激活，默认激活
    color = models.CharField(max_length=7, blank=True, null=True, verbose_name="标签颜色")  # 可选颜色字段，格式如 #FF5733
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='tags', verbose_name="标签创建者")
    note_count = models.IntegerField(default=0, verbose_name="标签笔记数")  # 该标签下的笔记数量

    def __str__(self):
        return self.name  # 返回标签的名称作为模型的字符串表示

    class Meta:
        db_table = 'tag'  # 数据库表名
        verbose_name = '标签'  # 单数形式显示名称
        verbose_name_plural = '标签'  # 复数形式显示名称


class Category(models.Model):
    """笔记分类模型"""

    id = models.BigAutoField(primary_key=True)  # 分类唯一标识，自动递增
    name = models.CharField(max_length=255, unique=True, verbose_name="分类名称")  # 分类名称，唯一
    description = models.TextField(blank=True, null=True, verbose_name="分类描述")  # 分类描述
    parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='subcategories', verbose_name="父分类")  # 父分类，用于支持树形结构
    order = models.IntegerField(default=0, verbose_name="排序字段")  # 排序字段
    icon = models.CharField(max_length=50, blank=True, null=True, verbose_name="图标")  # 分类图标
    color = models.CharField(max_length=7, blank=True, null=True, verbose_name="分类颜色")  # 分类颜色
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")  # 创建时间
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")  # 更新时间
    is_active = models.BooleanField(default=True, verbose_name="是否激活")  # 分类是否激活

    def __str__(self):
        return self.name  # 返回分类名称作为模型的字符串表示

    class Meta:
        db_table = 'category'  # 数据库表名
        verbose_name = '分类'  # 单数形式显示名称
        verbose_name_plural = '分类'  # 复数形式显示名称
        ordering = ['order']  # 默认按排序字段排序


class NoteTag(models.Model):
    """笔记标签关联模型"""

    id = models.BigAutoField(primary_key=True)  # 关联唯一标识，自动递增
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='note_tags', verbose_name="关联笔记")  # 关联笔记
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name='note_tags', verbose_name="关联标签")  # 关联标签
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")  # 创建时间 感觉没用

    def __str__(self):
        return f"{self.note.title} - {self.tag.name}"  # 返回关联的笔记标题和标签名称

    class Meta:
        db_table = 'note_tag'  # 数据库表名
        verbose_name = '笔记标签关联'  # 单数形式显示名称
        verbose_name_plural = '笔记标签关联'  # 复数形式显示名称
        unique_together = ['note', 'tag']  # 笔记和标签的组合唯一

class NoteCategory(models.Model):
    """笔记分类关联模型"""

    id = models.BigAutoField(primary_key=True)  # 关联唯一标识，自动递增
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='note_categories', verbose_name="关联笔记")  # 关联笔记
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='note_categories', verbose_name="关联分类")  # 关联分类
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")  # 创建时间 感觉没用

    def __str__(self):
        return f"{self.note.title} - {self.category.name}"  # 返回关联的笔记标题和分类名称

    class Meta:
        db_table = 'note_category'  # 数据库表名
        verbose_name = '笔记分类关联'  # 单数形式显示名称
        verbose_name_plural = '笔记分类关联'  # 复数形式显示名称
        unique_together = ['note', 'category']  # 笔记和分类的组合唯一


class NoteChat(models.Model):
    """用户与AI对话记录"""
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='chats')
    user_message = models.TextField(verbose_name="用户消息")
    ai_response = models.TextField(verbose_name="AI回复")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    #     user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='note_chats', verbose_name="用户")
    #     updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    #     status = models.CharField(max_length=20, choices=[('pending', '待处理'), ('processed', '已处理'), ('archived', '已归档')], default='pending', verbose_name="对话状态")
    #     session_id = models.CharField(max_length=255, null=True, blank=True, verbose_name="会话 ID")
    #     rating = models.IntegerField(null=True, blank=True, verbose_name="回复评分")
    #     model_version = models.CharField(max_length=50, default="gpt-3.5", verbose_name="AI 模型版本")
    #     message_type = models.CharField(max_length=20, choices=[('user', '用户消息'), ('ai', 'AI 回复'), ('system', '系统消息')], default='user', verbose_name="消息类型")

    def __str__(self):
        return f"{self.note.title} - {self.created_at}"

    class Meta:
        db_table = 'note_chat'
        verbose_name = '笔记对话记录'
        verbose_name_plural = '笔记对话记录'

class NoteHistory(models.Model):
    """笔记更新历史"""
    note = models.ForeignKey('Note', on_delete=models.CASCADE)
    change_type = models.CharField(max_length=50)
    old_content = models.TextField()
    new_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

class ChatHistory(models.Model):
    """对话历史记录"""
    MESSAGE_TYPES = (
        ('regular', '普通消息'),
        ('confirmation', '确认消息'),
        ('modification', '修改请求')
    )
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='chat_histories')
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='chat_histories')
    message = models.TextField()
    response = models.TextField()
    message_type = models.CharField(max_length=20, choices=MESSAGE_TYPES, default='regular')
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_at']
        verbose_name = '对话历史'
        verbose_name_plural = '对话历史'
    
    def __str__(self):
        return f"{self.user.username} - {self.note.title} - {self.created_at.strftime('%Y-%m-%d %H:%M')}"

class PendingChange(models.Model):
    """待确认的笔记更改"""
    note = models.ForeignKey(Note, on_delete=models.CASCADE, related_name='pending_changes')
    content = models.TextField(verbose_name='新内容')
    old_content = models.TextField(verbose_name='原内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '待确认更改'
        verbose_name_plural = '待确认更改'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'待确认更改 {self.id} - 笔记 {self.note_id}'